import { Component, OnInit } from '@angular/core'
import { Location } from '@angular/common'
import { Router } from '@angular/router'
import { CommonUtil } from 'src/app/common/utils/common.util'
import { LoginService } from 'src/app/common/services/login.service'

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {
  // 手机号码
  phone = ''
  // 发送验证码中
  loging = false

  constructor(
    private location: Location,
    private router: Router,
    private utils: CommonUtil,
    public loginService: LoginService
  ) {}

  ngOnInit() {}

  // 返回上一页
  onClickLeft() {
    this.location.back()
  }
  // 注册动作，完成基础数据校验
  registAction() {
    let phoneReg = /^1\d{10}$/
    let phoneNumber = this.phone
    if (!phoneReg.test(phoneNumber)) {
      this.utils.info('手机号格式错误，请重新输入')
    } else {
      this.registRequest()
    }
  }
  // 注册请求，发送验证码
  registRequest() {
    let reqdata = {
      mode: 'CaptchaMode_Mobile',
      target: this.phone
    }
    this.loging = true
    this.loginService.getCaptcha(
      reqdata,
      res => {
        let msg = '验证码发送失败，请重试'
        this.loging = false
        if (res.Success && res.Result) {
          this.utils.success('验证码已发送')
          this.router.navigate(['/login', { phone: this.phone }])
        } else {
          if (res.Message && res.Message.indexOf('|') > -1) {
            msg = res.Message.split('|')[0]
          }
          this.utils.info(msg)
        }
      },
      () => {
        this.loging = false
        this.utils.fail('网络异常，请重试')
      }
    )
  }
}
